<template>
  <div>
    <!-- 返利池管理 -->
    <TopFilter
      :list="topFilterList"
      :cols="3"
      @filterChange="changeHandle"
      @resetChange="resetChange"
      @onCollapse="collapseHandle"
      :labelWidth="110"
    ></TopFilter>

    <FilterTable
      ref="table"
      columnsRef="qjhRebatePoolQuery"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onCellChange="onCellChange"
      :onRowSelectChange="selectChangeHandle"
      :onSyncTableData="syncDataHandle"
      :mergeCellMethod="objectSpanMethod"
    >
      <template slot="controls">
        <multiuse-button size="small" type="primary" :disabled="isDisabled" :click="saveHandle">保 存</multiuse-button>
        <multiuse-button
          size="small"
          type="primary"
          :disabled="isDisabled"
          :click="allFreezeHandle"
        >全部冻结</multiuse-button>
        <multiuse-button size="small" type="primary" :click="importHandle">导入冻结</multiuse-button>
      </template>
    </FilterTable>
    <!-- 经销商查询 -->
    <BaseDialog
      :visible.sync="isDealer"
      title="经销商查询"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <OwnerSearch :rowData="formData" @close="emitCloseHandler" />
    </BaseDialog>

    <BaseDialog
      :visible.sync="isAmount"
      :title="'余额锁定明细'"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
      width="72%"
    >
      <DetailAmount :rowData="formData" @close="emitCloseHandler1" />
    </BaseDialog>

    <BaseDialog
      :visible.sync="UploadFileIsShow"
      title="导入"
      destroyOnClose
      :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }"
    >
      <!-- <UploadFile
        :action-url="actionUrl"
        :initial-value="form.fileList"
        :autoUpload='false'
        @change="successHandler"
        @error="errorHandler"
        :fileTypes="['xls','xlsx']"
      >选择导入文件
      </UploadFile>-->
      <!--<importFile-->
        <!--title="导入"-->
        <!--actionUrl="/api/cmscloud.wholesales/ttFiRebate/certificatePostImportFromExcel"-->
        <!--@close="closeImportHandler"-->
      <!--/>-->
      <!--<BaseDialog :visible.sync="visible" :title="'导入'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }">-->
        <importFiles @close="importcloseHandler" />
      <!--</BaseDialog>-->
    </BaseDialog>
    <BaseDialog :visible.sync="isFrostAmount" :title="'冻结明细查询'" destroyOnClose :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px' }" width="72%">
      <FreezeDetail :rowData="formData" @close="emitCloseHandler3" />
    </BaseDialog>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { getRegion } from '@/api/omFinance';
import { frostAll, updateFrostAmount, queryFrozenList, certificatePostImportFromExcel } from '@/api/omFinance/RebateManage/RebatePoolManage';
import { exportExcelFile, returnMoney } from '@/utils/index';
import { queryList } from '@/api/omFinance/RebateManage/ChildrenCapitalPoolQuery';
import DetailAmount from './DetailAmount';
import OwnerSearch from '../OwnerSearch';
import FreezeDetail from '../RebatePoolQuery/FreezeDetail';
import importFiles from './importFiles';
export default {
  name: 'RebatePoolQuery',
  mixins: [dictionary],

  data() {
    this.BaseTable = null;
    this.saveData = null;
    this.conf = { add: '新增', edit: '编辑', show: '明细' };
    return {
      topFilterList: this.createdFrom(),
      columns: this.createdTable(),
      fetchApi: queryList,
      fetchParams: {},
      formData: {},
      ids: [],
      isDealer: false,
      isAmount: false,
      isDisabled: true,
      exportLoading: false,
      isFrostAmount: false,
      UploadFileIsShow: false,
          form: {
        fileList: [],
        fileList_upload: []
      },
      handleType: '',
      drawerTitle: '',
      spanArr1: [], // 一个空的数组，用于存放每一行记录的合并数
      pos1: 0, // spanArr 的索引
      spanArr2: [], // 一个空的数组，用于存放每一行记录的合并数
      pos2: 0 // spanArr 的索引
    };
  },
  components: {
    DetailAmount,
    OwnerSearch,
    FreezeDetail,
    importFiles
  },
  mounted() {
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  created() {
    this.getDeptData();
  },
  methods: {
    importcloseHandler(val) {
      this.fetchParams = Object.assign({}, this.fetchParams);
      // this.fetchParams = { ...this.fetchParams }; //刷新
      this.UploadFileIsShow = false;
    },
    emitCloseHandler3(val) {
      this.isFrostAmount = val;
    },
    // 合并
    syncDataHandle(dataList) {
      if (!dataList.length) return;
      // 设定一个数组spanArr/contentSpanArr来存放要合并的格数，同时还要设定一个变量pos/position来记录
      this.spanArr1 = [];
      this.spanArr2 = [];
      for (let i = 0; i < dataList.length; i++) {
        if (i === 0) {
          this.spanArr1.push(1);
          this.pos1 = 0;
          this.spanArr2.push(1);
          this.pos2 = 0;
        } else {
          // 判断当前元素与上一个元素是否相同(第1列)
          if (dataList[i].dealerCode === dataList[i - 1].dealerCode) {
            this.spanArr1[this.pos1] += 1;
            this.spanArr1.push(0);
          } else {
            this.spanArr1.push(1);
            this.pos1 = i;
          }
          if (dataList[i].rebateTypeName === dataList[i - 1].rebateTypeName) {
            this.spanArr2[this.pos2] += 1;
            this.spanArr2.push(0);
          } else {
            this.spanArr2.push(1);
            this.pos2 = i;
          }
          console.log(JSON.stringify(this.spanArr1), this.pos1);
          console.log(JSON.stringify(this.spanArr2), this.pos2);
        }
      }
    },
    // 处理合并单元格
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 2 || columnIndex === 3 || columnIndex==4) {
        const _row = this.spanArr1[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      } else if (columnIndex === 5) {
        const _row = this.spanArr2[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return {
          rowspan: _row,
          colspan: _col
        };
      }
    },
        // 导入
    importHandle() {
      debugger
      this.handleType = 'import';
      this.UploadFileIsShow = true;
      this.form.fileList = [];
    },
    changeHandle(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    resetChange(params) {
      this.fetchParams = Object.assign({}, this.fetchParams, params);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    //加载事业部数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        res.data.map(x => {
          this.topFilterList.find(item => item.fieldName == 'deptId').itemList.push({ text: x.orgName, value: x.id });
        });
      }
    },
    // 导出
    async exportHandler() {
      await this.$confirm('是否将Excel表格保存至本地文件夹?', '提示', {
        confirmButtonText: '下载',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true;
          certificatePostImportFromExcel(this.fetchParams)
            .then(response => {
              exportExcelFile(response.data, '返利池查询');
              this.exportLoading = false;
            })
            .catch(err => {
              console.log(err);
            });
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          });
        });
    },
    onCellChange(columns, row) {
      // if (row.frostAmountNow==0){
      //   this.$message.warning('冻结金额不能为0！');
      //   row.frostAmountNow = 0;
      // }
      // if (row.frostAmountNow > row.availableAmount) {
      //   this.$message.warning('冻结金额不能大于可用余额！');
      //   row.frostAmountNow = 0;
      // }
    },
    closeImportHandler(val) {
      if (val && val.length > 0) {
        if (val[0].url.errorList && val[0].url.errorList.length > 0) {
        } else {
          this.form.fileList = val[0].url.clue;
        }
        // this.$message.success(val[0].url)
      }

      this.UploadFileIsShow = false;
      // 重新加载
      this.fetchParams = { ...this.fetchParams };
    },
    selectChangeHandle(rows) {
      console.log(rows, '---奥利给---');
      this.saveData = rows;
      this.ids = [];
      if (rows.length > 0) {
        this.isDisabled = false;
        rows.map(x => {
          this.ids.push(x.id);
        });
        return;
      }
      this.isDisabled = true;
    },
    // 保存
    async saveHandle() {
      let tempArr = [];
      let check=true;
      if (this.saveData.length > 0) {
        this.saveData.map(x => {
          if(!x.frostAmountNow||x.frostAmountNow==0){
            this.$notify({
              title: '警告',
              message: '冻结金额不正确',
              type: 'warning'
            });
            check=false;
            return;
          }
          if(x.remark){
            tempArr.push({ id: x.id, frostAmountNow: returnMoney(x.frostAmountNow), remark: x.remark });
          }else {
            this.$notify({
              title: '警告',
              message: '备注不可为空',
              type: 'warning'
            });
            check=false;
            return;
          }
        });
      }
      if(check) {
        this.isDisabled = true;
        console.log('tempArr', tempArr);
        const res = await updateFrostAmount(tempArr);
        if (res.resultCode == 200) {
          this.fetchParams = {...this.fetchParams};
        }else {
          this.isDisabled = false;
        }
      }
    },
    frostAmountHandle(row) {
      this.isFrostAmount = true;
      this.formData = row;
    },
    // 全部冻结
    async allFreezeHandle() {
      const res = await frostAll(this.ids);
      if (res.resultCode == 200) {
        this.fetchParams = { ...this.fetchParams };
      }
    },
    seacherFun() {
      this.isDealer = true;
    },
    emitCloseHandler(val, data) {
      this.isDealer = val;
      if (data) {
        let dealerCodes = [];
        let dealerNames = [];
        data.map(x => {
          dealerCodes.push(x.dealerCode);
          dealerNames.push(x.dealerName);
        });
        this.topFilterList.find(x => x.fieldName == 'dealerCode').initialValue = dealerCodes.toString();
      }
    },
    overHandle(row) {
      this.isAmount = true;
      this.formData = row;
    },
    emitCloseHandler1(val) {
      this.isAmount = val;
    },
    createdFrom() {
      return [
        {
          type: 'SELECT',
          label: '事业部',
          fieldName: 'deptId',
          placeholder: '请选择',
          itemList: []
        },
        {
          type: 'INPUT',
          label: '经销商代码',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          }
        },
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerName',
          placeholder: '请输入'
        },
        {
          type: 'SELECT',
          label: '是否有余额',
          fieldName: 'isAmount',
          placeholder: '请选择',
          itemList: this.createDictList('1004')
        },
        {
          type: 'SELECT',
          label: '动力形式',
          fieldName: 'powerType',
          placeholder: '请选择',
          itemList: this.createDictList('6008')
        }
      ];
    },
    createdTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 70,
          sorter: true,
          fixed: 'left',
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '事业部',
          dataIndex: 'deptName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商代码',
          dataIndex: 'dealerCode',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '经销商名称',
          dataIndex: 'dealerName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利账户类型',
          dataIndex: 'rebateTypeName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '返利子项目',
          dataIndex: 'rebateSubprojectsName',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '累计入账',
          dataIndex: 'totalInAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '累计出账',
          dataIndex: 'totalOutAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2
        },
        {
          title: '返利余额',
          dataIndex: 'balanceAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        // {
        //   title: '预扣金额',
        //   dataIndex: 'frozenAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   summation: true,
        //   precision: 2,
        //   numberFormat: true,
        //   render: props => {
        //     return (
        //       <el-link type="warning" underline={true} onClick={() => this.overHandle(props.row)}>
        //         {props.row.frozenAmount}
        //       </el-link>
        //     );
        //   }
        // },
        {
          title: '已冻结金额',
          dataIndex: 'frostAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: false,
          defaultEditable: false,
          editType: 'number',
          editRequired: true,
          summation: true,
          precision: 2,
          numberFormat: true,
          render: props => {
            return (
              <el-link type="warning" underline={true} onClick={() => this.frostAmountHandle(props.row)}>
                {props.row.frostAmount}
              </el-link>
            );
          }
        },
        {
          title: '当前可用余额',
          dataIndex: 'currentAvailableAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '冻结金额',
          dataIndex: 'frostAmountNow',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'number',
          editRequired: true,
          summation: true,
          precision: 2,
          numberFormat: true
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          filter: true,
          filterType: 'input',
          editable: true,
          defaultEditable: true,
          editType: 'text',
          editRequired: true
        },
        {
          title: '过期金额',
          dataIndex: 'overdueAmount',
          sorter: true,
          filter: true,
          filterType: 'input',
          summation: true,
          precision: 2,
          numberFormat: true
        },
        // {
        //   title: '可用余额',
        //   dataIndex: 'availableAmount',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'input',
        //   summation: true,
        //   precision: 2,
        //   numberFormat: true
        // },
        {
          title: '账户状态',
          dataIndex: 'status',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('1003'),
          render: props => {
            return <span>{this.createDictText(props.row.status, '1003')}</span>;
          }
        },
        {
          title: '最后更新日期',
          dataIndex: 'updatedAt',
          sorter: true,
          filter: true,
          filterType: 'date-range'
        }
      ];
    }
  }
};
</script>
